using System;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using RabbitMQ.Client.Events;

namespace CHEnhanceEfCore.Config.MQ.listen
{
    [MqListen("order")]
    public class OrderQueueListen : IQueueListen, IDisposable
    {
        readonly CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
        private CancellationToken cancellationToken;

        public void startHandleMessage(EventingBasicConsumer eventingBasicConsumer, Action<ulong, bool> action)
        {
            cancellationToken = cancellationTokenSource.Token;
            //注释的代码 是一些公用的已提
            Task.Run(() =>
            {
                eventingBasicConsumer.Received += (model, e) =>
                {
                    var readOnlyMemory = e.Body;
                    var message = Encoding.UTF8.GetString(readOnlyMemory.Span);
                    Console.WriteLine("Received===>" + message);
                    action?.Invoke(e.DeliveryTag, false);
                    //channel.BasicAck(e.DeliveryTag, false);
                };
                // channel.BasicConsume("task_queue", false, eventingBasicConsumer);
            }, cancellationToken);
        }

        public Task handleMessage(BasicDeliverEventArgs eventArgs)
        {
            return Task.CompletedTask;
        }

        public void Dispose()
        {
            //中断任务
            cancellationTokenSource.Cancel();
        }
    }
}